package logic

import (
	"context"
	"fmt"
	"muke-network/srv/model/mysql"
	"muke-network/srv/pkg"
	"strconv"

	"muke-network/srv/internal/svc"
	"muke-network/srv/muke"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *muke.CreateOrderRequest) (*muke.CreateOrderResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}

	err := g.FindGoods(in.GoodsId)
	if err != nil {
		logx.Error("商品详情展示失败")
		return nil, fmt.Errorf("商品详情展示失败")
	}

	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, fmt.Errorf("商品不存在")
	}
	o := mysql.Order{
		Userid:  in.UserId,
		GoodsId: in.GoodsId,
		OrderSn: in.OrderSn,
		Amount:  float64(in.Amount),
	}
	err = o.Create()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, fmt.Errorf("订单创建失败")
	}

	amount := strconv.FormatFloat(o.Amount, 'f', 1, 64)

	pay := pkg.Pay(g.GoodsName, o.OrderSn, amount)

	return &muke.CreateOrderResponse{
		OrderId: int64(o.ID),
		Url:     pay,
	}, nil
}
